package org.dawning.shop.inventory.query.handler;

import org.axonframework.eventhandling.EventHandler;
import org.dawning.shop.common.events.inventory.*;
import org.dawning.shop.inventory.query.entry.InventoryEntry;
import org.dawning.shop.inventory.query.repository.InventoryRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.security.auth.login.AccountException;

/**
 * Created by Cc on 2017/6/13.
 */
@Component
public class InventoryEntryHandler {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private InventoryRepository inventoryRepository;

    @EventHandler
    public void on(InventoryCreateEvent event){
        logger.info("create a new account event: "+event);
        inventoryRepository.save(new InventoryEntry(event.getId(),event.getAmount(),event.getWarnAmount()));
    }

    @EventHandler
    public void on(InventoryAddEvent event){
        logger.info("add productAmount for product: "+event);
        InventoryEntry inventoryEntry = inventoryRepository.findOne(event.getInventoryId());
        inventoryEntry.setAmount(inventoryEntry.getAmount()+event.getQuantity());
        inventoryRepository.save(inventoryEntry);
    }

    @EventHandler
    public void on(InventorySubtractEvent event){
        logger.info("update query subtract: "+event);
        InventoryEntry inventoryEntry = inventoryRepository.findOne(event.getInventoryId());
        inventoryEntry.setAmount(inventoryEntry.getAmount()-event.getQuantity());
        inventoryRepository.save(inventoryEntry);
    }

    @EventHandler
    public void on(InventoryReserveEvent event){
        logger.info("update query reserve: "+event);
        InventoryEntry inventoryEntry = inventoryRepository.findOne(event.getInventoryId());
        inventoryEntry.setAmount(inventoryEntry.getAmount()-event.getQuantity());
        inventoryRepository.save(inventoryEntry);
    }

    @EventHandler
    public void on(InventoryReleaseEvent event){
        logger.info("update query reserve add: "+event);
        InventoryEntry inventoryEntry = inventoryRepository.findOne(event.getInventoryId());
        inventoryEntry.setAmount(inventoryEntry.getAmount()-event.getQuantity());
        inventoryRepository.save(inventoryEntry);
    }
}
